<?php

namespace app\nav\controller;


use app\nav\model\NavCate;
use library\Controller;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;

/**
 * Class Cate
 * @package app\nav\controller
 * @auth true
 */
class Cate extends Controller
{
    /**
     * 数据表
     * @var string
     */
    protected $table = "nav_cate";

    /**
     * 导航分类管理
     * @auth true
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws PDOException
     */
    public function index()
    {
        $this->title = '导航分类管理';
        $query       = $this->_query($this->table)->like('name')->equal('type');
        $query->order('sort asc,id desc')->page();
    }

    /**
     * 添加分类
     * @auth true
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws PDOException
     */
    public function add()
    {
        $this->title = '添加分类';
        $this->_form($this->table, 'form');
    }

    /**
     * 编辑分类
     * @auth true
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws PDOException
     */
    public function edit()
    {
        $this->title = '编辑分类';
        $this->_form($this->table, 'form');
    }

    /**
     * 保存前置验证
     * @param $data
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {
            $q = NavCate::where('code', $data['code']);
            if (array_key_exists('id', $data)) {
                $q = $q->where('id', '<>', $data['id']);
            }
            if ($q->find()) {
                $this->error('编码已存在');
            }
        }
    }

    /**
     * 删除分类
     * @auth true
     * @throws Exception
     * @throws PDOException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }
}